package cn.z2huo.knowledge.concurrency.queue;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * <p>
 *
 * @author z2huo
 */
@Slf4j
class BlockingQueuePutTest {

    private static final int QUEUE_CAPACITY = 5;

    @Getter
    private final BlockingQueue<String> queue = new ArrayBlockingQueue<>(QUEUE_CAPACITY);

    public static void main(String[] args) {
        BlockingQueuePutTest test = new BlockingQueuePutTest();

        boolean flag = test.getQueue().addAll(List.of("a", "b", "c", "d", "e"));
        if (flag) {
            log.info("addAll element to queue success, queue is {}", test.getQueue());
        }

        try {
            boolean addFlag = test.getQueue().add("f");
            if (addFlag) {
                log.info("add element to queue success");
            }
        } catch (Exception e) {
            log.error("add element to queue error, queue is full, size is {} \n", test.getQueue().size(), e);
        }

        boolean offerFlag = test.getQueue().offer("g");
        if (offerFlag) {
            log.info("offer element to queue success");
        } else {
            log.info("offer element to queue fail, queue is full, size is {}", test.getQueue().size());
        }

        try {
            // 队列已满，put() 方法会阻塞，直到有空间加入队列
            test.getQueue().put("h");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

}
